package com.oversea.interceptor;

import java.lang.reflect.Method;
import java.util.Map;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.oversea.action.BaseAction;
import com.oversea.annotation.Permission;
import com.oversea.util.Constants;

public class PermissionInterceptor extends AbstractInterceptor {

	/**
	 * 
	 */
	private static final long serialVersionUID = -1347234037053570783L;

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		Action action = (Action)invocation.getProxy().getAction();
		String methodName = invocation.getProxy().getMethod();
		String url = invocation.getProxy().getNamespace();
		Method method = action.getClass().getMethod(methodName, new Class[] {});
		Permission permission = method.getAnnotation(Permission.class);
		if (permission == null) { //如果方法没有设定权限，则检查package的权限
			permission = action.getClass().getAnnotation(Permission.class);
		}
		if (permission == null) {
			return invocation.invoke();
		}
//		if (hasPermission(permission)) {
			return invocation.invoke();
//		}
//		return "NoPermission";
	}

	private boolean hasPermission(Permission permission) {
		Map<String, Object> session = ActionContext.getContext().getSession();
		if (session == null) {
			return false;
		}
		Integer level = (Integer) session.get(Constants.LOGIN_USER_ROLE_LEVEL_KEY);
		if (level == null) {
			return false;
		}
		if (level >= permission.level()) {
			return true;
		}
		return false;
	}

}
